package cn.jg.framework.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author fanfeveryahoo@gmail.com
 * @date 2019/3/20
 */
public class WebUtils {

	private WebUtils() {

	}

	public static String getRemoteAddr(HttpServletRequest request) {
		String remoteAddr = request.getHeader("X-Real-IP");
		if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("X-Forwarded-For");
		}
		if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getRemoteAddr();
		}
		if ("127.0.0.1".equals(remoteAddr) || remoteAddr.endsWith("0:0:0:0:0:0:1")) {
			try {
				remoteAddr = InetAddress.getLocalHost().getHostAddress();
			} catch (UnknownHostException e) {
				//
			}
		}
		if (StringUtils.isNotBlank(remoteAddr) && remoteAddr.length() > 15 && remoteAddr.contains(",")) {
			remoteAddr = remoteAddr.substring(0, remoteAddr.indexOf(','));
		}
		return remoteAddr;
	}
}
